package com.byzk.p2p.admin.base.filter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * <li>带验证码校验功能的用户名、密码认证过滤器</li>
 *
 * @author suker.zhou
 * 
 */
public class UsernamePasswordAuthenticationExtendFilter extends UsernamePasswordAuthenticationFilter {

	// 验证码字段  
	public static final String SPRING_SECURITY_FORM_VALIDATE_KEY = "j_validate";
	
	private String validateParameter = SPRING_SECURITY_FORM_VALIDATE_KEY;
    // 是否开启验证码功能  
    private boolean openValidateCode = true;  
  
    @Override  
    public Authentication attemptAuthentication(HttpServletRequest request,  
            HttpServletResponse response) throws AuthenticationException {  
        // 只接受POST方式传递的数据  
        if (!"POST".equals(request.getMethod())){
			try {
				throw new Exception("不支持非POST方式的请求!");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}         	
        }
  
        // 开启验证码功能的情况  
        if (isOpenValidateCode()){
        	try {
				checkValidateCode(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
  
        // 获取Username和Password  
        String username = obtainUsername(request);  
        String password = obtainPassword(request);  
  
        // UsernamePasswordAuthenticationToken实现Authentication校验  
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(  
                username, password);  
  
        // 允许子类设置详细属性  
        setDetails(request, authRequest);  
  
        // 运行UserDetailsService的loadUserByUsername 再次封装Authentication  
        return this.getAuthenticationManager().authenticate(authRequest);  
    }  
  
    // 匹对验证码的正确性  
    public void checkValidateCode(HttpServletRequest request,HttpServletResponse response) throws Exception {  
    	//用户输入的验证码
        String jcaptchaCode = obtainValidateCodeParameter(request); 
        //系统session储存的验证码
        String session_code=(String) request.getSession().getAttribute("jcaptchaCode");
        
        if(StringUtils.isBlank(jcaptchaCode) || !jcaptchaCode.equals(session_code)){
        	response.sendRedirect("/login?error=3");
        	//throw new LoginExeption("验证码不匹配");
        }
    }  
  
    public String obtainValidateCodeParameter(HttpServletRequest request) {  
        Object obj = request.getParameter(validateParameter);  
        return null == obj ? "" : obj.toString().trim();  
    }  
  
    @Override  
    protected String obtainUsername(HttpServletRequest request) {  
        Object obj = request.getParameter(getUsernameParameter());  
        return null == obj ? "" : obj.toString().trim();  
    }  
  
    @Override  
    protected String obtainPassword(HttpServletRequest request) {  
        Object obj = request.getParameter(getPasswordParameter());  
        return null == obj ? "" : obj.toString().trim();  
    }  
  
    public boolean isOpenValidateCode() {  
        return openValidateCode;  
    }  
  
    public void setOpenValidateCode(boolean openValidateCode) {  
        this.openValidateCode = openValidateCode;  
    }  
  
}  

